package com.harisucici.app;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.harisucici.app.databinding.ActivityMainBinding;
import com.harisucici.jetpackbase.base.HBaseActivity;
import com.harisucici.jetpackbase.broadcast.MessageReceiver;
import com.harisucici.skywarp.SkywarpListener;
import com.harisucici.skywarp.SkywarpObserver;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends HBaseActivity<ActivityMainBinding, MainModel> implements SkywarpListener {

    private String[] titles = {"Tab0", "Tab1", "Tab2"};
    private MessageReceiver receiver;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static int REQUEST_PERMISSION_CODE = 1;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
                SkywarpObserver.getInstance().startObserve(this, this);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
        SkywarpObserver.getInstance().startObserve(this, this);

    }

    @Override
    public void initParam() {
        super.initParam();
        addDialog(DialogTest.TAG, new DialogTest());

    }


    private class ViewPagerAdapter extends FragmentStateAdapter {

        public ViewPagerAdapter(@NonNull @NotNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        public ViewPagerAdapter(@NonNull @NotNull Fragment fragment) {
            super(fragment);
        }

        public ViewPagerAdapter(@NonNull @NotNull FragmentManager fragmentManager, @NonNull @NotNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NonNull
        @NotNull
        @Override
        public Fragment createFragment(int position) {
            if (position == 0) {
                return new Fragment1();
            } else if (position == 1) {
                return new Fragment2();
            } else if (position == 2) {
                return new Fragment1();
            } else {
                return null;
            }
        }

        @Override
        public int getItemCount() {
            return 3;
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.testDelayMsg.observeInActivity(this, s -> {
        });
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewmodel;
    }

    @Override
    public void initData(View v) {
        viewModel.title.set("傻逼111");


        ViewPagerAdapter adapter = new ViewPagerAdapter(this);
        binding.viewPager.setAdapter(adapter);
        new TabLayoutMediator(binding.tabLayout, binding.viewPager, true,new TabLayoutMediator.TabConfigurationStrategy(){
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles[position]);
            }
        }).attach();


//        showDialog(DialogTest.TAG);

//        startActivity(new Intent(this,ThirdActivity.class));
//        startActivity(ThirdActivity.class);

//        startContainerActivity(Fragment1.class.getCanonicalName());
//        Bundle bundle=new Bundle();
//        bundle.putString("dashabi","dashabi11111");

//        startContainerActivity(Fragment2.class);

//        startActivity4Result(SecondActivity.class);

    }

    @Override
    public void editFile(File file) {
        String s = file.getPath();
        Glide.with(this).asBitmap().load(file).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull @NotNull Bitmap resource, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                int height = resource.getHeight();
                int width = resource.getWidth();
                String s = resource.toString();
                Log.e("bit", height + "::" + width);
                Bitmap bitmap2 = addTextWatermark(resource, "大傻逼", 200, Color.RED, width, height, true);
                save(bitmap2, file, Bitmap.CompressFormat.JPEG, true);
            }

            @Override
            public void onLoadCleared(@Nullable @org.jetbrains.annotations.Nullable Drawable placeholder) {

            }
        });
//                file.delete();
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }

//    @Override
//    public void onLaunchFourResult(ActivityResult result) {
//        super.onLaunchFourResult(result);
//
//        showSnack(result.getData().getStringExtra("MAP_VIEW_KEY"), SnackbarUtil.ALERT);
//    }

    private Bitmap addTextWatermark(Bitmap src, String content, int textSize, int color, float x, float y, boolean recycle) {
        if (isEmptyBitmap(src) || content == null) {
            return null;
        }
        Bitmap ret = src.copy(src.getConfig(), true);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        Canvas canvas = new Canvas(ret);

        Paint paint1 = new Paint();
        paint1.setColor(Color.BLACK);
        paint1.setStyle(Paint.Style.FILL);
        canvas.drawRect(0, 0, x, y, paint1);


        paint.setColor(color);
        paint.setTextSize(textSize);
        Rect bounds = new Rect();
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, 20, y / 2, paint);
        if (recycle && !src.isRecycled()) {
            src.recycle();
        }
        return ret;
    }

    private boolean save(Bitmap src, File file, Bitmap.CompressFormat format, boolean recycle) {
        if (isEmptyBitmap(src)) {
            return false;
        }

        OutputStream os;
        boolean ret = false;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            ret = src.compress(format, 100, os);
            if (recycle && !src.isRecycled()) {
                src.recycle();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

    private boolean isEmptyBitmap(Bitmap src) {
        return src == null || src.getWidth() == 0 || src.getHeight() == 0;
    }
}